﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace GameNesSL.Views
{
    using System.IO;
    using System.Threading;
    using nesemu;
    using WebRef;

    public partial class GamePage : Page
    {
        private GameFieldConfig cfg;

        public GamePage()
        {
            InitializeComponent();
            playerControls.Play += new EventHandler(playerControls_Play);
            playerControls.Paused += new EventHandler(playerControls_Paused);
            playerControls.Mute += new EventHandler(playerControlsSoundChange);
            playerControls.Unmute += new EventHandler(playerControlsSoundChange);
            cfg = GameContext.webMethods.GetConfig()??new GameFieldConfig();
            game.Configure(cfg);
            cfg.Events.StateLoaded += new NotifyDelegate(Events_StateLoaded);
            cfg.Events.StateSaved += new StateSavedDelegate(Events_StateSaved);
        }

        void playerControlsSoundChange(object sender, EventArgs e)
        {
            game.ToggleSound();
            Cache.GameCache.SetConfig(cfg);
        }

        void Events_StateSaved(byte[] saveData)
        {
            GameContext.stats.TimesSaved++;
            savedPulse.Start();
            ThreadPool.QueueUserWorkItem(DoSave, saveData);
        }

        void Events_StateLoaded()
        {
            GameContext.stats.Timesloaded++;
            restoredPulse.Start();
        }



  
        private void DoSave(object state)
        {
            //Save to web here
            byte[] data = (byte[])state;
            Cache.GameCache.Save(GameContext.webMethods.GameID, data);
        }

        private bool IsUserHasGameSlot()
        {
            return false;
        }

        void playerControls_Paused(object sender, EventArgs e)
        {
            pausePulse.Start();
            game.TogglePause();
            embeddLink.Visibility = System.Windows.Visibility.Visible;
        }

        void playerControls_Play(object sender, EventArgs e)
        {
            pausePulse.Stop();
            game.TogglePause();
            embeddLink.Visibility = System.Windows.Visibility.Collapsed;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //Load game
            try
            {
                if (GameContext.RomData != null)
                {
                    embeddLink.EmbedID = GameContext.webMethods.GameID;
                    load.Visibility = System.Windows.Visibility.Collapsed;
                    using (MemoryStream ms = new MemoryStream(GameContext.RomData))
                    {
                        game.LoadRom(ms);

                    }
                    Cache.GameCache.CacheRom(GameContext.webMethods.GameID, GameContext.RomData);//Save only normal roms^)

                    game.Start();

                    if (GameContext.SaveData != null)
                    {
                        //Can resume
                        cfg.LoadData = GameContext.SaveData;
                        game.LoadState(GameContext.ShouldLoadState);
                    }
                    GameContext.SignalGameLoaded();
                    GameContext.stats.TimePlayedStart = DateTime.UtcNow;
                }
            }
            catch (Exception ex)
            {
                GameContext.SignalGameError();
                GameContext.ErrorDescription = "Bad rom image "+ex.Message;
                NavigationService.Navigate(new Uri("/Error", UriKind.Relative));
            }
            
        }

        private void load_Click(object sender, MouseButtonEventArgs e)
        {
            load.Visibility = System.Windows.Visibility.Collapsed;
            OpenFileDialog dlg = new OpenFileDialog { Filter = "NES Roms (*.nes)|*.nes", Multiselect = false };
            if (dlg.ShowDialog().GetValueOrDefault(false))
            {
                game.LoadRom(dlg.File.OpenRead());
                game.Start();
            }
        }

        private void saveSound_Click(object sender, MouseButtonEventArgs e)
        {
            //game.SaveSound();
        }
    }
}
